package com.xujl.task;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

/**
 * <pre>
 *     @author : xujl
 *     e-mail : 597355068@qq.com
 *     time   : 2018/7/23
 *     desc   :
 *     version: 1.0
 * </pre>
 */
class RxHandler extends Handler {
    private static final String TAG = "RxHandler";

    static RxHandler getInstance () {
        return Holder.RX_HANDLER;
    }

    private RxHandler () {
        super(Looper.getMainLooper());
    }

    @Override
    public void handleMessage (Message msg) {
        super.handleMessage(msg);
        final Object obj = msg.obj;
        if (!(obj instanceof RxMessage)) {
            RxLog.d(TAG, "Task:  Message isNot Task");
            return;
        }
        RxMessage rxMessage = (RxMessage) obj;
        final Task task = rxMessage.getTask();
        if (task == null || task.isDestroy()) {
            RxLog.d(TAG, "Task:  task.isDestroy");
            return;
        }
        String taskId = task.getTaskId();
        try {
            switch (msg.what) {
                case Emitter.ERROR:
                    final Exception exception = (Exception) rxMessage.getObj();
                    RxLog.i(TAG, "Task--" + taskId + ":Emitter.ERROR:" + exception.getMessage());
                    task.onError(exception);
                    break;
                case Emitter.NEXT:
                    if (rxMessage.getObj() != null) {
                        RxLog.i(TAG, "Task--" + taskId + ":Emitter.ObjNEXT");
                        task.onObjNext(rxMessage.getObjCode(), rxMessage.getObj());
                    } else {
                        RxLog.i(TAG, "Task--" + taskId + ":Emitter.NEXT");
                        task.onNext(rxMessage.getData());
                    }
                    break;
                case Emitter.UI:
                    RxLog.i(TAG, "Task--" + taskId + ":Emitter.UI");
                    task.onlyRunUiTask();
                    break;
                case Emitter.FINISH:
                    RxLog.i(TAG, "Task--" + taskId + ":Emitter.FINISH");
                    task.onFinished();
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            RxLog.e(TAG, "RxTask执行异常：" + e);
        }

    }

    private static class Holder {
        private static final RxHandler RX_HANDLER = new RxHandler();
    }
}
